package com.ljkj.cordial.chat.presenter.response;

import android.app.Activity;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.lanjiu.lib.imclient.bus.EventConstants;
import com.lanjiu.lib.imclient.bus.MessageEvent;
import com.lanjiu.lib.imclient.dto.extra.UserChatTable;
import com.lanjiu.lib.imclient.ims.IMSContacts;
import com.lanjiu.lib.imclient.ims.IMSUtils;
import com.lanjiu.lib.imclient.user.UserPreferences;
import com.lanjiu.pro.business.BusinessProtocolEntities;
import com.lanjiu.pro.business.BusinessProtocolMessages;
import com.ljkj.cordial.chat.base.ChatApp;
import com.ljkj.cordial.chat.bean.Canstants;
import com.ljkj.cordial.chat.bean.EmptyMessageEvent;
import com.ljkj.cordial.chat.bean.MsgType;
import com.ljkj.cordial.chat.dao.ChatTableBean;
import com.ljkj.cordial.chat.dao.UserTableBean;
import com.ljkj.cordial.chat.dao.notify.BusinessLeaveTable;
import com.ljkj.cordial.chat.dao.notify.ChatContentTable;
import com.ljkj.cordial.chat.dao.notify.GroupMemberTable;
import com.ljkj.cordial.chat.dao.notify.GroupTable;
import com.ljkj.cordial.chat.notify.NotificationHelper;
import com.ljkj.cordial.chat.notify.NotificationUtils;
import com.ljkj.cordial.chat.ui.ChatUtils;
import com.ljkj.cordial.chat.util.AlbumManageUtil;
import com.ljkj.cordial.chat.util.SpeechVoiceUtil;

import org.greenrobot.eventbus.EventBus;

public class GroupChatProtocolResponse extends AResponseBusinessPresenter {
    private Activity activity;

    @Override
    public void onResponse(Activity activity, boolean isOnScreen, String msgType, Object msg) {
        this.activity = activity;
        BusinessProtocolMessages.GroupChatProtocol response = (BusinessProtocolMessages.GroupChatProtocol) msg;
        BusinessProtocolEntities.ChatMessage chatMessage = response.getChatMessage();
        BusinessProtocolEntities.TouristsGroupMember touristsGroupMember = response.getTouristsGroupMember();
        BusinessProtocolEntities.RegisteredGroupMember registeredGroupMember = response.getRegisteredGroupMember();
        BusinessProtocolEntities.TouristsUser touristsUser = response.getTouristsUser();
        BusinessProtocolEntities.RegisteredUser registeredUser = response.getRegisteredUser();
        GroupTable groupTable = null;
        GroupMemberTable groupMemberTable = null;
        if (response.hasTouristsGroupMember()) {
            if (touristsGroupMember.hasGroup()) {
                groupTable = getTouristsGroup(touristsGroupMember.getGroup());
                if (TextUtils.isEmpty(groupTable.getGroupOwnerId())) {
                    groupTable.setGroupOwnerId(GroupMemberTable.OWNER == touristsGroupMember.getGroupMemberType() ? touristsGroupMember.getGroupMemberUserId() : "");
                }
//                if (!ChatApp.getInstance().getUserId().equals(touristsGroupMember.getGroupMemberUserId())) {
                groupMemberTable = getGroupMemberTable(groupTable.getGroupId(), groupTable.getGroupName(), IMSContacts.UserType.TOURISTS_USER, touristsGroupMember.getGroupMemberId(), touristsGroupMember.getGroupMemberName(), touristsGroupMember.getGroupMemberNick(), touristsGroupMember.getGroupMemberUserId(), touristsGroupMember.getGroupMemberAlias(), touristsGroupMember.getOnlineStatus(), IMSContacts.UserType.TOURISTS_USER, touristsGroupMember.getGroupMemberAvatar(), touristsGroupMember.getGroupMemberType());
//                }
            }
        } else if (response.hasRegisteredGroupMember()) {
            if (registeredGroupMember.hasGroup()) {
                groupTable = getRegisteredGroup(registeredGroupMember.getGroup());
                if (TextUtils.isEmpty(groupTable.getGroupOwnerId())) {
                    groupTable.setGroupOwnerId(GroupMemberTable.OWNER == touristsGroupMember.getGroupMemberType() ? touristsGroupMember.getGroupMemberUserId() : "");
                }
//                if (!ChatApp.getInstance().getUserId().equals(registeredGroupMember.getGroupMemberUserId())) {
                groupMemberTable = getGroupMemberTable(groupTable.getGroupId(), groupTable.getGroupName(), IMSContacts.UserType.REGISTERED_USER, registeredGroupMember.getGroupMemberId(), registeredGroupMember.getGroupMemberName(), registeredGroupMember.getGroupMemberNick(), registeredGroupMember.getGroupMemberUserId(), registeredGroupMember.getGroupMemberAlias(), registeredGroupMember.getOnlineStatus(), IMSContacts.UserType.REGISTERED_USER, registeredGroupMember.getGroupMemberAvatar(), registeredGroupMember.getGroupMemberType());
//                }
            }
        }
        if (response.hasChatMessage() && groupMemberTable != null && groupTable != null && !TextUtils.isEmpty(groupMemberTable.getGroupMemberUserId())) {
            ChatTableBean chatTableBean = new ChatTableBean();
            chatTableBean.setChatName(groupTable.getGroupId());
            chatTableBean.setFromType(Canstants.GROUP_CHAT);
            chatTableBean.setGroupId(groupTable.getGroupId());
            chatTableBean.setGroupType(groupTable.getGroupType());
            chatTableBean.setMsgId(chatMessage.getMsgId());
            chatTableBean.setTargetId(groupMemberTable.getGroupMemberUserId());
            chatTableBean.setTargetName(!TextUtils.isEmpty(groupMemberTable.getGroupMemberAlias()) ? groupMemberTable.getGroupMemberAlias() : groupMemberTable.getGroupMemberName());
            chatTableBean.setTargetType(groupMemberTable.getUserType());
            chatTableBean.setSendType(ChatTableBean.RECEIVE);
            chatTableBean.setChatUnRead(ChatTableBean.UNREAD);
            chatTableBean.setSendState(ChatTableBean.SEND_SUCCESS);
            chatTableBean.setChatAvatarUrl(groupMemberTable.getGroupMemberAvatar());
            chatTableBean.setReadFinishTime(groupTable.getSnapchatTimeLength());
            chatTableBean.setStartReadFinish(groupTable.getSnapchatStatus());
            chatTableBean.setMsgTime(System.currentTimeMillis());
            chatTableBean.setHistoryTime(ChatUtils.analysisTimestampInMessageId(chatMessage.getMsgId()));
            chatTableBean.setAtelIds(response.getAt());

            if (chatMessage.hasFile()) {
                BusinessProtocolEntities.File file = chatMessage.getFile();
                String url = file.getUrl();
                chatTableBean.setFileUrl(url);
                chatTableBean.setFileLength(file.getLength());
                chatTableBean.setChatType(MsgType.ANNEX);
                insert(groupTable, groupMemberTable, chatTableBean);
            } else if (chatMessage.hasPicture()) {
                BusinessProtocolEntities.Picture pic = chatMessage.getPicture();
                chatTableBean.setFileUrl(pic.getUrl());
                chatTableBean.setChatType(MsgType.Picture);
                chatTableBean.setThumbPath(AlbumManageUtil.getImagePathByByteString(pic.getThumbnail()));
                insert(groupTable, groupMemberTable, chatTableBean);
            } else if (chatMessage.hasText()) {
                BusinessProtocolEntities.Text txt = chatMessage.getText();
                chatTableBean.setChatType(MsgType.Text);
                chatTableBean.setTextMsg(txt.getContent());
                if (chatMessage.getChatType() > 9) {//留言
                    BusinessLeaveTable table = new BusinessLeaveTable();
                    table.setTargetGroupId(groupTable.getGroupId());
                    table.setTargetGroupName(groupTable.getGroupName());
                    table.setTargetGroupType(groupTable.getGroupType());
                    table.setTargetUserType(groupMemberTable.getUserType());
                    table.setTargetUserId(groupMemberTable.getGroupMemberUserId());
                    table.setTargetUserName(groupMemberTable.getGroupMemberName().replaceAll(",", "、"));
                    table.setAvatarUrl(groupMemberTable.getGroupMemberAvatar());
                    table.setTargetStatus(chatMessage.getChatType());
                    table.setMsgId(chatMessage.getMsgId());
                    table.setTargetLeave(table.getTargetStatus(), table.getTargetUserId(), table.getTargetGroupName());
                    if (chatMessage.getChatType() == IMSContacts.MsgContentType.DELETE_GROUP_MEMBER) {
                        String memberId = groupMemberTable.getGroupMemberUserId();
                        if (!TextUtils.isEmpty(memberId) && memberId.contains(UserPreferences.getUserId())) {
                            GroupTable.deleteByGroupId(groupTable.getGroupId());
                            GroupMemberTable.deleteByGroupId(groupTable.getGroupId());
                            ChatTableBean.deleteByGroupId(groupTable.getGroupId());
                            ChatContentTable.deleteById(groupTable.getGroupId(), Canstants.GROUP_CHAT);
                            table.setTargetUserId(response.getRegisteredGroupMember().getGroupMemberNick());
                            table.setTargetUserName(response.getRegisteredGroupMember().getGroupMemberAlias());
                            table.setAvatarUrl(response.getRegisteredGroupMember().getUserType());
                        } else {
                            if (!TextUtils.isEmpty(memberId)) {
                                for (String mid : memberId.split(",")) {
                                    if (GroupMemberTable.deleteByUserId(groupTable.getGroupId(), mid)) {
                                        GroupTable.subMemberCount(groupTable.getGroupId());
                                    }
                                }
                            }
                        }
                        MessageEvent event = MessageEvent.cerateUiRefresh(EventConstants.Action.DELETE_GROUP);
                        event.setData(groupTable.getGroupId() + "_" + groupMemberTable.getGroupMemberUserId());
                        EventBus.getDefault().post(event);

                        NotificationUtils.notifyGroup(activity, groupTable, groupMemberTable, NotificationHelper.NTYPE_GROUP_DELETE);
                    } else if (chatMessage.getChatType() == IMSContacts.MsgContentType.EXIT_GROUP) {
                        if (GroupMemberTable.deleteByUserId(groupTable.getGroupId(), groupMemberTable.getGroupMemberUserId())) {
                            GroupTable.subMemberCount(groupTable.getGroupId());
                        }
                        MessageEvent event = MessageEvent.cerateUiRefresh(EventConstants.Action.EXIT_GROUP);
                        event.setData(groupTable.getGroupId() + "_" + groupMemberTable.getGroupMemberUserId());
                        EventBus.getDefault().post(event);

                        NotificationUtils.notifyGroup(activity, groupTable, groupMemberTable, NotificationHelper.NTYPE_GROUP_EXIT);
                    } else if (chatMessage.getChatType() == IMSContacts.MsgContentType.DISSOLVE_GROUP) {
                        GroupTable.deleteByGroupId(groupTable.getGroupId());
                        GroupMemberTable.deleteByGroupId(groupTable.getGroupId());
                        ChatTableBean.deleteByGroupId(groupTable.getGroupId());
                        MessageEvent event = MessageEvent.cerateUiRefresh(EventConstants.Action.DISSOLVE_GROUP);
                        event.setData(groupTable.getGroupId());
                        EventBus.getDefault().post(event);

                        NotificationUtils.notifyGroup(activity, groupTable, groupMemberTable, NotificationHelper.NTYPE_GROUP_DISSOLVE);
                    } else if (chatMessage.getChatType() == IMSContacts.MsgContentType.APPLY_TOURISTS ||
                            chatMessage.getChatType() == IMSContacts.MsgContentType.APPLY_REGISTERED) {
                        NotificationUtils.notifyGroup(activity, groupTable, groupMemberTable, NotificationHelper.NTYPE_GROUP_APPLY);
                    } else if (chatMessage.getChatType() == IMSContacts.MsgContentType.INVITE_REFUSE_TOURISTS ||
                            chatMessage.getChatType() == IMSContacts.MsgContentType.INVITE_REFUSE_REGISTERED) {
                        NotificationUtils.notifyGroup(activity, groupTable, groupMemberTable, NotificationHelper.NTYPE_GROUP_REFUSE);
                    }
                    BusinessLeaveTable.insert(table, BusinessLeaveTable.GROUP_LEAVE);
                    if (isOnScreen) {
                        refresh(activity);
                    }
                    return;
                }
//                GroupTable finalGroupTable = groupTable;
//                GroupMemberTable finalGroupMemberTable = groupMemberTable;
//                EmojiPackage.handlerEmojiText(txt.getContent(), new EmojiPackage.OnSpannableListener() {
//                    @Override
//                    public void deCode(SpannableStringBuilder text) {
//                        chatTableBean.setTextMsg(txt.getContent());
//                        chatTableBean.setCharSequenceText(TextCharSequenceTran.create(text));
//                        insert(finalGroupTable, finalGroupMemberTable, chatTableBean);
//                    }
//                });
                chatTableBean.setTextMsg(txt.getContent());
                insert(groupTable, groupMemberTable, chatTableBean);
            } else if (chatMessage.hasVoice()) {
                BusinessProtocolEntities.Voice voi = chatMessage.getVoice();
                chatTableBean.setChatType(MsgType.Voice);
                chatTableBean.setThumbPath(SpeechVoiceUtil.analysisPath(voi.getContent()));
                chatTableBean.setChatAvatarId(String.valueOf(SpeechVoiceUtil.analysisDuration(chatTableBean.getThumbPath())));
                insert(groupTable, groupMemberTable, chatTableBean);
            } else if (chatMessage.hasVideo()) {
                BusinessProtocolEntities.Video vid = chatMessage.getVideo();
                chatTableBean.setChatType(MsgType.Video);
                chatTableBean.setFileUrl(vid.getUrl());
                chatTableBean.setThumbPath(AlbumManageUtil.getImagePathByByteString(vid.getThumbnail()));
                insert(groupTable, groupMemberTable, chatTableBean);
            }
        }
//        NotificationUtils.messageNotify(activity);
        NotificationUtils.notifyGroup(activity, groupTable, groupMemberTable, NotificationHelper.NTYPE_GROUP_CHAT);
    }

    /**
     * 成员是自己
     *
     * @param groupMemberTable
     */
    public void setGroupMemberUserTable(GroupMemberTable groupMemberTable) {
        UserTableBean user = UserTableBean.getCurrentUser();
        groupMemberTable.setGroupMemberNick(user.getNickname());
        groupMemberTable.setGroupMemberAvatar(user.getAvatar());
        groupMemberTable.setGroupMemberUserId(ChatApp.getInstance().getUserId());
        groupMemberTable.setUserType(IMSUtils.userTypeAnalysis(groupMemberTable.getGroupMemberUserId()));
    }

    private GroupMemberTable setGroupMemberTable(GroupMemberTable groupMemberTable, String nickname, String avatar, String groupMemberUserId, String userType) {
        if (!TextUtils.isEmpty(nickname)) {
            groupMemberTable.setGroupMemberNick(nickname);
        }
        if (!TextUtils.isEmpty(avatar)) {
            groupMemberTable.setGroupMemberAvatar(avatar);
        }
        if (!TextUtils.isEmpty(groupMemberUserId)) {
            groupMemberTable.setGroupMemberUserId(groupMemberUserId);
        }
        groupMemberTable.setUserType(IMSUtils.userTypeAnalysis(groupMemberUserId));
        return groupMemberTable;
    }

    private GroupMemberTable getGroupMemberTable(String groupId, String groupName, String groupType, String groupMemberId, String groupMemberName, String groupMemberNick, String groupMemberUserId, String groupMemberAlias, String onlineStatus, String userType, String groupMemberAvatar, int groupMemberType) {
        GroupMemberTable groupMemberTable = GroupMemberTable.create(groupId, groupMemberUserId);
        if (ChatApp.getInstance().getUserId().equals(groupMemberUserId)) {
            setGroupMemberUserTable(groupMemberTable);
        } else {
            setGroupMemberTable(groupMemberTable, groupMemberNick, groupMemberAvatar, groupMemberUserId, userType);
        }
        groupMemberTable.setGroupId(groupId);
        groupMemberTable.setGroupName(groupName);
        groupMemberTable.setGroupType(groupType);

        groupMemberTable.setGroupMemberType(groupMemberType);
        groupMemberTable.setGroupMemberId(groupMemberId);
        groupMemberTable.setGroupMemberName(groupMemberName);
//        groupMemberTable.setGroupMemberAlias(groupMemberAlias);
        groupMemberTable.setOnlineStatus(onlineStatus);
        return groupMemberTable;
    }

    private GroupTable getRegisteredGroup(BusinessProtocolEntities.RegisteredGroup group) {
        GroupTable groupTable = GroupTable.queryRowByGroupIdNotNull(group.getGroupId());
        if (TextUtils.isEmpty(groupTable.getGroupName()))
            groupTable.setGroupName(group.getGroupName());
        groupTable.setGroupId(group.getGroupId());
        groupTable.setGroupType(IMSContacts.UserType.REGISTERED_USER);
        if (group.hasGroupAnnouncements()) {
            BusinessProtocolEntities.GroupAnnouncements groupS = group.getGroupAnnouncements();
            groupTable.setAnnouncementContent(groupS.getAnnouncementContent());
            groupTable.setAnnouncementTitle(groupS.getAnnouncementTitle());
            groupTable.setAnnouncementId(groupS.getAnnouncementId());
        }
        if (group.hasSettings()) {
            BusinessProtocolEntities.Settings set = group.getSettings();
            groupTable.setSnapchatStatus(set.getSnapchatStatus());
            groupTable.setSnapchatTimeLength(set.getSnapchatTimeLength());
            groupTable.setSnapchatTimeUnit(set.getSnapchatTimeUnit());
        }
        return groupTable;
    }

    private GroupTable getTouristsGroup(BusinessProtocolEntities.TouristsGroup group) {
        GroupTable groupTable = GroupTable.queryRowByGroupIdNotNull(group.getGroupId());
        if (TextUtils.isEmpty(groupTable.getGroupName()))
            groupTable.setGroupName(group.getGroupName());
        groupTable.setGroupId(group.getGroupId());
        groupTable.setGroupType(IMSContacts.UserType.TOURISTS_USER);
        groupTable.setGroupOwnerId(group.getGroupOwnerUserId());
        if (group.hasGroupAnnouncements()) {
            BusinessProtocolEntities.GroupAnnouncements groupS = group.getGroupAnnouncements();
            groupTable.setAnnouncementContent(groupS.getAnnouncementContent());
            groupTable.setAnnouncementTitle(groupS.getAnnouncementTitle());
            groupTable.setAnnouncementId(groupS.getAnnouncementId());
        }
        if (group.hasSettings()) {
            BusinessProtocolEntities.Settings set = group.getSettings();
            groupTable.setSnapchatStatus(set.getSnapchatStatus());
            groupTable.setSnapchatTimeLength(set.getSnapchatTimeLength());
            groupTable.setSnapchatTimeUnit(set.getSnapchatTimeUnit());
        }
        return groupTable;
    }

    @Override
    public void insert(Object... table) {
        try {
            GroupTable groupTable = (GroupTable) table[0];
            GroupMemberTable groupMemberTable = (GroupMemberTable) table[1];
            ChatTableBean chatTableBean = (ChatTableBean) table[2];
            GroupTable.insertNoUpdate(groupTable);
            GroupMemberTable.insertOrUpdate(groupMemberTable);
            ChatTableBean.insertWhenMsgIdNotExist(chatTableBean);

            ChatContentTable cct = ChatContentTable.queryRowByTargetIdNotNull(groupTable.getGroupId(), Canstants.GROUP_CHAT);
            cct.setChatType(Canstants.GROUP_CHAT);
            cct.setTargetId(groupTable.getGroupId());
            cct.setTargetName(groupTable.getGroupName());
            cct.setTargetType(groupTable.getGroupType());
            String[] v = GroupMemberTable.getAvatarEntityLoc(groupTable.getGroupId());
            if (v != null) {
                cct.setTargetMemberUserId(v[0]);
                cct.setTargetAvatarUrl(v[1]);
                cct.setTargetAvatarPath(v[2]);
            }
            cct.setLastMsgType(chatTableBean.getChatType());
            cct.setLastMsg(chatTableBean.getTextMsg());
            cct.setIsSnapchat(chatTableBean.getStartReadFinish() ? 1 : 0);
            cct.setIsRead(0);
            cct.setUpdateTime(chatTableBean.getHistoryTime());
            cct.setAtelIds(chatTableBean.getAtelIds());
            ChatContentTable.insert(cct);
            update(groupTable, groupMemberTable, chatTableBean, cct);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void update(Object... table) {
        super.update(table);
        GroupTable groupTable = (GroupTable) table[0];
        GroupMemberTable groupMemberTable = (GroupMemberTable) table[1];
        ChatTableBean chatTable = (ChatTableBean) table[2];
        ChatContentTable cct = (ChatContentTable) table[3];
//        if (!TextUtils.isEmpty(groupMemberTable.getGroupMemberAvatar())) {
//            if (activity != null && !activity.isFinishing()) {
//                activity.runOnUiThread(() ->
//                                AlbumManageUtil.getInstance().downLoadFileFriend(groupMemberTable.getGroupMemberAvatar(), AlbumTableBean.TYPE_AVATAR, groupMemberTable.getGroupMemberUserId(), new AlbumManageUtil.OnFileResponse() {
//                                    @Override
//                                    public void onResult(String path, String fileId) {
//                                        ObserverThread.create().onNextThread1(new ObserverThread.OnMulActionListener() {
//                                            @Override
//                                            public void onAction(Object... obj) {
//                                                refresh(activity);
//                                            }
//
//                                            @Override
//                                            public Object[] onThreadAction() {
//                                                try {
//                                                    AlbumTableBean al = AlbumTableBean.queryById(Long.valueOf(fileId));
//                                                    String path = TextUtils.isEmpty(al.getMThumbPath()) ? al.getMPath() : al.getMThumbPath();
//                                                    DaoSession dbSession = DbController.getInstance().getWrite();
//                                                    groupMemberTable.setGroupMemberAvatarId(fileId);
//                                                    groupMemberTable.setGroupMemberAvatarPath(path);
//                                                    dbSession.getGroupMemberTableDao().update(groupMemberTable);
//                                                    chatTable.setChatAvatarId(fileId);
//                                                    chatTable.setChatAvatarPath(path);
//                                                    dbSession.getChatTableBeanDao().update(chatTable);
////                                            cct.setAvatarId(fileId);
////                                            cct.setTargetAvatarPath(path);
////                                            dbSession.getChatContentTableDao().update(cct);
//                                                    MessageEvent event = MessageEvent.cerateUiRefresh(EventConstants.Action.CHAT_REFRESH);
//                                                    UserChatTable ucha = new UserChatTable(groupTable.getGroupId(), groupTable.getGroupName(), Canstants.GROUP_CHAT, chatTable.isStartReadFinish(), chatTable.getChatType(), chatTable.getTextMsg(), chatTable.getMsgTime());
//                                                    ucha.setReceiveType(UserChatTable.RECEIVE_FROM_NET);
//                                                    event.setData(new Gson().toJson(ucha));
//                                                    EventBus.getDefault().post(event);
//
//                                                    postEvent(new EmptyMessageEvent(Canstants.GROUP_CHAT, groupTable.getGroupId(), groupTable.getGroupName(), groupTable.getGroupType(), groupMemberTable.getGroupMemberUserId(), chatTable.getMsgId()));
//                                                } catch (Exception e) {
//                                                    e.printStackTrace();
//                                                }
//                                                return new Object[0];
//                                            }
//                                        });
//                                    }
//                                })
//
//                );
//            }
//            return;
//        } else {
        MessageEvent event = MessageEvent.cerateUiRefresh(EventConstants.Action.CHAT_REFRESH);
        UserChatTable ucha = new UserChatTable(groupTable.getGroupId(), groupTable.getGroupName(), Canstants.GROUP_CHAT, chatTable.isStartReadFinish(), chatTable.getChatType(), chatTable.getTextMsg(), chatTable.getHistoryTime());
        ucha.setReceiveType(UserChatTable.RECEIVE_FROM_NET);
        event.setData(new Gson().toJson(ucha));
        EventBus.getDefault().post(event);

        postEvent(new EmptyMessageEvent(Canstants.GROUP_CHAT, groupTable.getGroupId(), groupTable.getGroupName(), groupTable.getGroupType(), groupMemberTable.getGroupMemberUserId(), chatTable.getMsgId()));

        refresh(activity);
//        }
    }
}
